package com.wenx.v3system.modular.platform.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wenx.v3dynamicdatasourcestarter.config.DynamicDataSourceConfig;
import com.wenx.v3system.modular.platform.domain.po.PlatformUserRole;
import com.wenx.v3system.modular.platform.mapper.PlatformUserRoleMapper;
import com.wenx.v3system.modular.platform.service.PlatformRoleService;
import com.wenx.v3system.modular.platform.service.PlatformUserRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 平台用户角色关联服务实现类
 * 使用lambda chain方式实现简化的权限管理
 * 使用v3-platform数据源
 * 
 * @author wenx
 */
@Slf4j
@Service
@RequiredArgsConstructor
@DS(DynamicDataSourceConfig.PLATFORM_DATASOURCE)
public class PlatformUserRoleServiceImpl extends ServiceImpl<PlatformUserRoleMapper, PlatformUserRole> implements PlatformUserRoleService {

    private final PlatformRoleService platformRoleService;

    @Override
    public List<String> getRoleCodesByUserId(Long userId) {
        return this.list(
            new LambdaQueryWrapper<PlatformUserRole>()
                .eq(PlatformUserRole::getUserId, userId)
        ).stream()
        .map(PlatformUserRole::getRoleCode)
        .distinct()
        .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignUserRoles(Long userId, List<String> roleIds) {
        if (userId == null || roleIds == null || roleIds.isEmpty()) {
            return;
        }
        // 删除用户现有角色
        removeUserRoles(userId);

        // 将角色ID转换为角色代码
        List<String> roleCodes = platformRoleService.getRoleCodesByIds(roleIds);
        if (roleCodes.isEmpty()) {
            log.warn("未找到有效的角色代码: roleIds={}", roleIds);
            return;
        }
        List<PlatformUserRole> userRoles = roleCodes.stream()
            .map(roleCode -> {
                PlatformUserRole userRole = new PlatformUserRole();
                userRole.setUserId(userId);
                userRole.setRoleCode(roleCode);
                return userRole;
            })
            .collect(Collectors.toList());
        
        this.saveBatch(userRoles);
        log.info("用户角色分配成功: userId={}, roleCount={}", userId, roleCodes.size());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeUserRoles(Long userId) {
        this.remove(
            new LambdaQueryWrapper<PlatformUserRole>()
                .eq(PlatformUserRole::getUserId, userId)
        );
        log.info("删除用户所有角色: userId={}", userId);
    }
}